package logic

import (
	"context"
	"fmt"
	"shuqi_novel/models"
	"shuqi_novel/pkg"

	"shuqi_novel/shop_rpc/internal/svc"
	"shuqi_novel/shop_rpc/shop_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shop_rpc.LoginRequest) (*shop_rpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if models.DB.Where("account = ?", in.Account).Limit(1).Find(&user).Error != nil {
		return &shop_rpc.LoginResponse{}, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		return &shop_rpc.LoginResponse{}, fmt.Errorf("账号不存在")
	}
	if user.Password != in.Password {
		return &shop_rpc.LoginResponse{}, fmt.Errorf("密码错误")
	}
	handler, err := pkg.TokenHandler(fmt.Sprintf("%d", user.ID))
	if err != nil {
		return &shop_rpc.LoginResponse{}, fmt.Errorf("服务器繁忙")

	}
	return &shop_rpc.LoginResponse{
		Token: handler,
	}, nil
}
